//
//  UICloseButton.swift
//  DragonWallet
//
//  Created by volantPig on 2024/5/31.
//

import UIKit

class UICloseButton: UIButton {
    
    var placeholderStr: String = "add_placeholder"
    var closeBtn: UIButton?
    var observation: NSKeyValueObservation?
    var closeCompleted: (()->Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.closeBtn = UIButton(type: .custom)
        self.addSubview(self.closeBtn!)
        self.closeBtn?.snp.makeConstraints({ make in
//            make.centerX.equalTo(self.snp.right)
//            make.centerY.equalTo(self.snp.top)
//            make.size.equalTo(CGSize(width: 20, height: 20))
            make.right.top.equalTo(self)
            make.size.equalTo(CGSize(width: 19, height: 19))
        })
        self.closeBtn?.setImage(UIImage(named: "close_button")?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.closeBtn?.addTarget(self, action: #selector(closeAction), for: .touchUpInside)
        
        self.addObservation()
    }
    
    func addObservation() {
        self.observation = observe(\.imageView?.image, changeHandler: {[weak self] selfButton, change in
            
            if selfButton.currentImage == UIImage(named: self?.placeholderStr ?? "") {
                printLog("666555888,占位图")
                self?.closeBtn?.isHidden = true
            } else {
                printLog("666555888,新图片")
                self?.closeBtn?.isHidden = false
            }
            
        })
    }
    
    @objc func closeAction() {
        printLog("关闭")
//        self.setImage(UIImage(named: self.placeholderStr), for: .normal)
        self.closeCompleted?()
    }
     
    /// 归0操作
    func refrehPlaceholder() {
        self.setImage(UIImage(named: self.placeholderStr), for: .normal)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
